package cn.com.ry.framework.linklog.resttemplate.filter;

import cn.com.ry.framework.linklog.constant.LinkLogConstants;
import cn.com.ry.framework.linklog.context.LinkLogContext;
import cn.com.ry.framework.linklog.context.SpanIdGenerator;
import cn.com.ry.framework.linklog.util.HostInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

public class LinkLogRestTemplateFilter implements ClientHttpRequestInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LinkLogRestTemplateFilter.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        String traceId = LinkLogContext.getTraceId();
        if (traceId != null && !traceId.equals("")) {
            httpRequest.getHeaders().set(LinkLogConstants.LINKLOG_TRACE_KEY, traceId);
            httpRequest.getHeaders().set(LinkLogConstants.LINKLOG_SPANID_KEY, SpanIdGenerator.generateNextSpanId());
            httpRequest.getHeaders().set(LinkLogConstants.LINKLOG_PRE_APP_KEY, HostInfo.getAppName());
            httpRequest.getHeaders().set(LinkLogConstants.LINKLOG_PRE_HOST_KEY, HostInfo.getHostName());
            httpRequest.getHeaders().set(LinkLogConstants.LINKLOG_PRE_IP_KEY, HostInfo.getIp());
        } else {
            logger.debug("[LinkLog]本地threadLocal变量没有正确传递traceId,本次调用不传递traceId");
        }
        return clientHttpRequestExecution.execute(httpRequest, body);
    }
}
